package com.nuorui.module.supper.dict.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuorui.common.constant.AdminCacheConst;
import com.nuorui.common.core.domain.ResponseDTO;
import com.nuorui.common.utils.SmartBeanUtil;
import com.nuorui.module.supper.dict.mapper.DictMapper;
import com.nuorui.module.supper.dict.mapper.DictDataMapper;
import com.nuorui.module.supper.dict.domain.entity.DictDataEntity;
import com.nuorui.module.supper.dict.domain.entity.DictEntity;
import com.nuorui.module.supper.dict.domain.form.*;
import com.nuorui.module.supper.dict.domain.vo.DictDataVO;
import com.nuorui.module.supper.dict.domain.vo.DictVO;
import com.nuorui.module.supper.dict.manager.DictManager;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * 数据字典 Service
 *
 * @Author 1024创新实验室-主任-卓大
 * @Date 2025-03-25 22:25:04
 * @Copyright <a href="https://1024lab.net">1024创新实验室</a>
 */

@Service
public class DictService {

    @Resource
    private DictMapper dictMapper;

    @Resource
    private DictDataMapper dictDataMapper;

    @Resource
    private CacheManager cacheManager;

    @Resource
    private DictManager dictManager;


    /**
     * 分页查询
     */
    public IPage<DictVO> getDictPage(Page page, DictQueryForm queryForm) {
        return page.setRecords(dictMapper.selectDictPage(page, queryForm));
    }

    /**
     * 获取所有字典
     */
    public List<DictVO> getDictList(DictQueryForm queryForm) {
        return dictMapper.selectDictList(queryForm);
    }

    /**
     * 添加
     */
    public  ResponseDTO<String> saveDict(DictForm addForm) {
        DictEntity existDictCode = dictMapper.selectByCode(addForm.getDictCode());
        if (null != existDictCode) {
            return ResponseDTO.userErrorParam("数据字典编码已经存在！");
        }

        DictEntity dictEntity = SmartBeanUtil.copy(addForm, DictEntity.class);
        dictMapper.insert(dictEntity);
        return ResponseDTO.ok();
    }

    /**
     * 禁用  启用
     */
    public ResponseDTO<String> updateDisabled(Long dictId) {
        DictEntity dictEntity = dictMapper.selectById(dictId);
        if (dictEntity == null) {
            return ResponseDTO.userErrorParam("数据不存在");
        }

        dictEntity.setDisabledFlag(!dictEntity.getDisabledFlag());
        dictMapper.updateById(dictEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     */
    @CacheEvict(AdminCacheConst.Dict.DICT_DATA)
    public ResponseDTO<String> updateDict(Long dictId, DictForm dictForm) {
        DictEntity existDictCode = dictMapper.selectByCode(dictForm.getDictCode());
        if (null != existDictCode && !existDictCode.getDictId().equals(dictId)) {
            return ResponseDTO.userErrorParam("数据字典编码已经存在！");
        }

        DictEntity dictEntity = SmartBeanUtil.copy(dictForm, DictEntity.class);
        dictEntity.setDictId(dictId);

        dictMapper.updateById(dictEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    @CacheEvict(AdminCacheConst.Dict.DICT_DATA)
    public ResponseDTO<String> batchDelete(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return ResponseDTO.ok();
        }

        dictMapper.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    @CacheEvict(AdminCacheConst.Dict.DICT_DATA)
    public ResponseDTO<String> deleteDict(Long dictId) {
        if (null == dictId) {
            return ResponseDTO.ok();
        }

        dictMapper.deleteById(dictId);
        return ResponseDTO.ok();
    }


    // -------------- 字典数据 --------------------

    /**
     * 获取字典数据
     */
    public List<DictDataVO> getByDictId(Long dictId) {
        return dictDataMapper.selectByDictId(dictId);
    }

    /**
     * 获取全部字典数据
     */
    public List<DictDataVO> getDictDataList() {
        return dictDataMapper.selectDictDataList();
    }

    /**
     * 获取字典
     */

    public DictDataVO getDictData(String dictCode, String dataValue) {
        return dictManager.getDictData(dictCode, dataValue);
    }

    /**
     * 获取字典Label
     */
    public String getDictDataLabel(String dictCode, String dataValue) {
        DictDataVO dictData = getDictData(dictCode, dataValue);
        return dictData == null ? "" : dictData.getDataLabel();
    }

    /**
     * 添加
     */
    public ResponseDTO<String> saveDictData(DictDataForm addForm) {

        addForm.setDataValue(StrUtil.trim(addForm.getDataValue()));

        DictEntity dictEntity = dictMapper.selectById(addForm.getDictId());
        if (null == dictEntity) {
            return ResponseDTO.userErrorParam("数据字典不存在");
        }

        DictDataEntity existData = dictDataMapper.selectByDictIdAndValue(addForm.getDictId(), addForm.getDataValue());
        if (null != existData) {
            return ResponseDTO.userErrorParam("已存在相同value的数据");
        }

        DictDataEntity dictDataEntity = SmartBeanUtil.copy(addForm, DictDataEntity.class);

        dictDataMapper.insert(dictDataEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     */
    @CacheEvict(value = AdminCacheConst.Dict.DICT_DATA, key = "#updateForm.dictCode + '_' + #updateForm.dataValue")
    public ResponseDTO<String> updateDictData(Long dictDataId,DictDataForm dataForm) {

        dataForm.setDataValue(StrUtil.trim(dataForm.getDataValue()));

        DictEntity dictEntity = dictMapper.selectById(dataForm.getDictId());
        if (null == dictEntity) {
            return ResponseDTO.userErrorParam("数据字典不存在");
        }

        DictDataEntity existData = dictDataMapper.selectByDictIdAndValue(dataForm.getDictId(), dataForm.getDataValue());
        if (null != existData && !existData.getDictDataId().equals(dictDataId)) {
            return ResponseDTO.userErrorParam("已存在相同value的数据");
        }

        DictDataEntity dictDataEntity = SmartBeanUtil.copy(dataForm, DictDataEntity.class);
        dictDataEntity.setDictDataId(dictDataId);
        dictDataMapper.updateById(dictDataEntity);

        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDeleteDictData(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return ResponseDTO.ok();
        }

        // 删除
        dictDataMapper.deleteBatchIds(idList);
        clearDictDataCache(idList);

        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> deleteDictData(Long dictDataId) {
        if (null == dictDataId) {
            return ResponseDTO.ok();
        }

        // 删除
        dictDataMapper.deleteById(dictDataId);
        clearDictDataCache(Collections.singletonList(dictDataId));

        return ResponseDTO.ok();
    }


    /**
     * 清空字典数据缓存
     */
    private void clearDictDataCache(List<Long> idList) {
        List<DictDataVO> dictDataList = dictDataMapper.selectByDictDataIds(idList);
        Cache cache = cacheManager.getCache(AdminCacheConst.Dict.DICT_DATA);
        if (cache == null) {
            return;
        }

        for (DictDataVO dictDataVO : dictDataList) {
            cache.evict(dictDataVO.getDictCode() + "_" + dictDataVO.getDataValue());
        }
    }


    /**
     * 更新启用/禁用
     */
    public  ResponseDTO<String> updateDictDataDisabled(Long dictDataId) {
        DictDataEntity dictDataEntity = dictDataMapper.selectById(dictDataId);
        if (dictDataEntity == null) {
            return ResponseDTO.userErrorParam("数据不存在");
        }

        dictDataEntity.setDisabledFlag(!dictDataEntity.getDisabledFlag());

        dictDataMapper.updateById(dictDataEntity);
        return ResponseDTO.ok();
    }

}
